<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter';

import { Button, message, Popconfirm, Dropdown } from 'ant-design-vue';
import { $t } from '#/locales';
import { useVbenVxeGrid } from '#/adapter';
import { ref, onMounted, watch, nextTick } from 'vue';
import {
  ArrowLeftOutlined,
  SaveOutlined,
  EyeOutlined,
  SortAscendingOutlined,
  MenuOutlined
} from '@ant-design/icons-vue';
import ModelDrawer from './model-drawer.vue';
import { useVbenDrawer } from '@vben/common-ui';
import { type FieldConfig } from '#/api/core/lowcode';
import PublishComponent from '../publish/single-page.vue';

// 修改表格数据类型
const tableData = ref<FieldConfig[]>([]);
const originalData = ref<FieldConfig[]>([]);

// 添加组件类型映射
const componentTypeMap = {
  'Input': '输入框',
  'Textarea': '多行文本',
  'Select': '单项选择框',
  'SelectMultiple': '多项选择框',
  'Radio': '单选按钮',
  'Checkbox': '多选按钮',
  'DatePicker': '日期选择',
  'TimePicker': '时间选择',
  'DateTimePicker': '日期时间选择',
  'InputNumber': '数字输入',
  'Password': '密码输入',
  'ImageUpload': '图片上传',
  'FileUpload': '文件上传',
  'ImagePreview': '图片预览',
  'FilePreview': '文件预览'
};

const gridOptions: VxeGridProps<FieldConfig> = {
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { field: 'field', title: '字段名' },
    { field: 'title', title: '标题' },
    {
      field: 'component',
      title: '组件类型',
      formatter: ({ cellValue }) => {
        return componentTypeMap[cellValue as keyof typeof componentTypeMap] || cellValue;
      }
    },
    { field: 'helper', title: '帮助信息' },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: $t('common.action.name'),
      width: 180,
    },
  ],
  data: tableData.value,
  height: 'auto',
  sortConfig: {
    multiple: true,
  },
  showOverflow: true,
  showHeaderOverflow: true,
  pagerConfig: {
    enabled: false
  },
};

// 添加状态管理
const currentEditData = ref<FieldConfig | undefined>();
const drawerSaveCallback = ref<((data: FieldConfig) => void) | undefined>();

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

// 返回列表
function handleBack() {
  emit('update:showDesign', false);
}

// 添加预览状态
const isPreview = ref(false);
const previewData = ref({});

// 修改预览函数
function handlePreview() {
  previewData.value = {
    fields: tableData.value,
    tableName: props.designer?.tableName,
    layout: props.designer?.layout,
    name: props.designer?.name,
    isPreview: true
  };
  isPreview.value = true;
}

// 添加返回设计函数
function handlePreviewBack() {
  isPreview.value = false;
}

// 构建表单配置的 JSON
function buildFormConfig() {
  const formFields = tableData.value.map(item => {
    const field = { ...item };
    delete field._X_ROW_KEY;
    return field;
  });

  const formConfig = {
    fields: formFields,
    tableName: props.designer?.tableName,
    layout: props.designer?.layout,
    version: '1.0',
    updateTime: new Date().toISOString(),
  };

  return formConfig;
}

// 添加更新设计器数据的函数
function updateDesignerContext() {
  if (!props.designer) {
    message.error('设计器数据不存在');
    return;
  }

  // 构建表单配置
  const formConfig = buildFormConfig();

  // 将配置转换为 JSON 字符串
  const configJson = JSON.stringify(formConfig);

  // 更新设计器数据
  const updatedDesigner = {
    ...props.designer,
    context: configJson,  // 保存到 context 字段
  };

  // 触发更新事件
  emit('update:designer', updatedDesigner);
}

// 修改保存函数
async function handleSave() {
  try {
    updateDesignerContext();
    message.success($t('common.action.saveSuccess'));
  } catch (error) {
    console.error('保存失败:', error);
    message.error($t('common.action.saveFailed'));
  }
}

// 添加字段名称重复检查函数
function checkFieldNameDuplicate(fieldName: string, currentField?: FieldConfig): boolean {
  return tableData.value.some(item =>
    item.field === fieldName && (!currentField || item.field !== currentField.field)
  );
}

// 修改 handleAdd 函数
function handleAdd() {
  currentEditData.value = undefined;
  drawerSaveCallback.value = (formData: FieldConfig) => {
    if (checkFieldNameDuplicate(formData.field)) {
      message.error(`字段名 "${formData.field}" 已存在，请修改后重试`);
      return false;
    }

    // 清空并重新赋值
    const newData = [...tableData.value, formData];
    tableData.value.length = 0;
    newData.forEach(field => tableData.value.push(field));
    gridApi.reload();
    message.success($t('common.action.addSuccess'));
    return true;
  };
  baseDrawerApi.open();
}

// 修改 handleEdit 函数
function handleEdit(row: FieldConfig) {
  const plainData = { ...row };
  currentEditData.value = plainData;
  drawerSaveCallback.value = (formData: FieldConfig) => {
    // 检查字段名是否重复（跳过自身）
    if (checkFieldNameDuplicate(formData.field, row)) {
      message.error(`字段名 "${formData.field}" 已存在，请修改后重试`);
      return false; // 返回 false 表示保存失败，抽屉不会关闭
    }

    const index = tableData.value.findIndex(item => item.field === row.field);
    if (index > -1) {
      tableData.value[index] = { ...formData };
      gridApi.reload();
      message.success($t('common.action.editSuccess'));
      return true; // 返回 true 表示保存成功，抽屉会关闭
    }
    return false;
  };
  baseDrawerApi.open();
}

// 处理表格行删除
async function handleDelete(row: FieldConfig) {
  const index = tableData.value.findIndex(item => item.field === row.field);
  if (index > -1) {
    tableData.value.splice(index, 1);
  }
  gridApi.reload();
  message.success($t('common.action.deleteSuccess'));
}

const [BaseDrawer, baseDrawerApi] = useVbenDrawer({
  connectedComponent: ModelDrawer,
});

// 添加排序相关的状态
const sortVisible = ref(false);
const sortFields = ref<FieldConfig[]>([]);

// 添加拖拽相关状态
const dragItem = ref<FieldConfig | null>(null);

// 修改排序处理函数
function handleSort() {
  sortFields.value = [...tableData.value];
  sortVisible.value = true;
}

// 修改排序确认函数
function handleSortConfirm() {
  // 清空并重新赋值
  tableData.value.length = 0;
  sortFields.value.forEach(field => tableData.value.push(field));
  gridApi.grid.clearAll();
  gridApi.reload(tableData.value);
  sortVisible.value = false;
}

// 添加恢复默认函数
function handleSortReset() {
  sortFields.value = [...originalData.value];
}

// 修改拖拽处理函数
function handleDragStart(e: DragEvent, field: FieldConfig) {
  dragItem.value = field;
  if (e.dataTransfer) {
    e.dataTransfer.effectAllowed = 'move';
  }
}

function handleDragOver(e: DragEvent) {
  e.preventDefault();
  if (e.dataTransfer) {
    e.dataTransfer.dropEffect = 'move';
  }
}

function handleDrop(e: DragEvent, target: FieldConfig) {
  e.preventDefault();
  if (dragItem.value && dragItem.value !== target) {
    const oldIndex = sortFields.value.indexOf(dragItem.value);
    const newIndex = sortFields.value.indexOf(target);
    sortFields.value.splice(oldIndex, 1);
    sortFields.value.splice(newIndex, 0, dragItem.value);
  }
  dragItem.value = null;
}

// 定义props
const props = defineProps<{
  designer: DesignerModel | null;
  showDesign: boolean;
}>();

// 修改 emit 定义
const emit = defineEmits<{
  (e: 'update:showDesign', value: boolean): void;
  (e: 'update:designer', value: DesignerModel): void;
}>();

interface DesignerModel {
  id?: number;
  name?: string;
  redirect?: string;
  description?: string;
  context?: string;
  layout?: string;
  tableName?: string;
}

// 添加布局类型映射
const layoutOptions = {
  single: '单页布局',
  navigation: '导航布局',
  multi: '多条件布局',
};

// 修改 initFormData 函数，同时保存原始数据
function initFormData() {
  if (props.designer?.context) {
    try {
      const config = JSON.parse(props.designer.context);
      if (config.fields && Array.isArray(config.fields)) {
        // 保存原始数据
        originalData.value = [...config.fields];
        // 设置表格数据
        tableData.value.length = 0;
        config.fields.forEach((field: FieldConfig) => tableData.value.push(field));
        gridApi.reload(tableData.value);
      }
    } catch (error) {
      console.error('初始化数据失败:', error);
      message.error('初始化数据失败');
    }
  }
}

// 在组件挂载时初始化数据
onMounted(() => {
  initFormData();
});

// 修改 tableData 的监听器
watch(
  tableData,
  () => {
    // 使用 nextTick 确保数据更新完成后再保存
    nextTick(() => {
      updateDesignerContext();
    });
  },
  { deep: true }
);
</script>

<template>
  <div class="design-container">
    <!-- 设计器模式 -->
    <template v-if="!isPreview">
      <!-- 标题栏 -->
      <div class="design-header">
        <div class="header-left">
          <Button @click="handleBack">
            <template #icon><ArrowLeftOutlined /></template>
            返回
          </Button>
          <span class="header-title">
            {{ props.designer?.name || '' }}设计 -
            <span v-if="props.designer?.layout" >
              {{ layoutOptions[props.designer.layout as keyof typeof layoutOptions] || props.designer.layout }}
            </span>
          </span>
        </div>
        <div class="header-extra">
          <Button title="预览" @click="handlePreview">
            <template #icon><EyeOutlined /></template>
          </Button>
          <Button title="保存" @click="handleSave">
            <template #icon><SaveOutlined /></template>
          </Button>
        </div>
      </div>
      <!-- 内容区 -->
      <div class="design-content">
        <BaseDrawer
          :edit-data="currentEditData"
          :on-save="drawerSaveCallback"
          :table-name="props.designer?.tableName"
          :table-data="tableData"
        />
        <Grid class="design-grid">
          <template #toolbar-actions>
            <Button class="mr-2" type="primary" @click="handleAdd">新增</Button>
          </template>
          <template #toolbar-tools>
            <div class="flex items-center">
              <Dropdown
                v-model:visible="sortVisible"
                :trigger="['click']"
              >
                <Button
                  class="ml-2"
                  title="字段排序"
                  @click="handleSort"
                >
                  <template #icon>
                    <SortAscendingOutlined />
                  </template>
                </Button>
                <template #overlay>
                  <div class="sort-dropdown bg-white p-4 shadow-lg rounded">
                    <div class="dropdown-title">字段排序</div>
                    <div class="min-w-[240px]">
                      <template v-for="field in sortFields" :key="field.field">
                        <div
                          class="field-item"
                          draggable="true"
                          @dragstart="(e) => handleDragStart(e, field)"
                          @dragover="handleDragOver"
                          @drop="(e) => handleDrop(e, field)"
                        >
                          <span>{{ field.title }}</span>
                          <div class="flex-1" />
                          <MenuOutlined />
                        </div>
                      </template>
                    </div>
                    <div class="flex justify-between mt-4">
                      <Button size="small" @click="handleSortReset">恢复默认</Button>
                      <div class="flex gap-2">
                        <Button size="small" @click="sortVisible = false">取消</Button>
                        <Button size="small" type="primary" @click="handleSortConfirm">确定</Button>
                      </div>
                    </div>
                  </div>
                </template>
              </Dropdown>
            </div>
          </template>
          <template #action="{ row }">
            <Button type="link" @click="handleEdit(row)">编辑</Button>
            <Popconfirm
              :title="$t('role.delete.confirm')"
              :cancel-text="$t('common.no')"
              :ok-text="$t('common.yes')"
              @confirm="handleDelete(row)"
            >
              <Button type="link" danger>删除</Button>
            </Popconfirm>
          </template>
        </Grid>
      </div>
    </template>

    <!-- 预览模式 -->
    <PublishComponent
      v-else
      v-bind="previewData"
      @back="handlePreviewBack"
    />
  </div>
</template>

<style lang="less" scoped>
.design-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;

  .design-header {
    flex: none;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 16px;
    border-bottom: 1px solid #f0f0f0;

    .header-left {
      display: flex;
      align-items: center;
      gap: 8px;

      .header-title {
        font-size: 16px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.85);

        .layout-tag {
          font-size: 12px;
          color: #666;
          margin-left: 8px;
          padding: 2px 8px;
          background: #f5f5f5;
          border-radius: 4px;
        }
      }
    }

    .header-extra {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }

  .design-content {
    flex: 1;
    padding: 24px;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .design-grid {
      width: 100%;
      height: 100%;

      :deep(.vxe-table--main-wrapper) {
        height: 100%;
      }
    }
  }
}

.sort-dropdown {
  min-width: 240px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 12px;

  .dropdown-title {
    font-size: 13px;
    margin-bottom: 8px;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 600;
  }

  .field-item {
    display: flex;
    align-items: center;
    padding: 4px 8px;
    font-size: 13px;
    background: #fff;
    cursor: move;

    &:hover {
      background: #f5f5f5;
    }

    .anticon {
      color: #bfbfbf;
      font-size: 12px;
    }
  }

  .ant-btn {
    font-size: 13px;
    padding: 2px 8px;
  }
}
</style>
